package com.ypx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypx.bean.*;
import com.ypx.common.BaseContext;
import com.ypx.mapper.OrdersMapper;
import com.ypx.exception.CustomException;
import com.ypx.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Tang
 * @date 2023/2/25
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 下单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //0.开启事务（涉及到orders订单表 、order_detail订单明细表两张表的更新操作）
        //1.获取当前登录的用户id
        Long userId = BaseContext.getCurrentId();

        //2.查询用户表，得到用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("该用户不存在！");
        }

        //3.构造订单明细数据 List<OrderDetail>
        List<OrderDetail> orderDetailList = new ArrayList<>();

        //3.1 查询购物车数据，根据当前用户id查，得到购物车列表
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(cartWrapper);
        if (cartList.isEmpty()) {
            throw new CustomException("请先添加商品到购物车！");
        }

        //3.2 循环购物车列表，将购物车数据拷贝给OrderDetail
        //使用工具类，生成订单id，底层使用的是雪花策略
        long orderId = IdWorker.getId();
        BigDecimal sumAmount = new BigDecimal(0);
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //3.3 设置订单id
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            //3.4 计算总金额 (累加每个商品的单价*数量)
            sumAmount = sumAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //4.构造订单数据 Orders
        //4.1 补齐字段
        orders.setId(orderId);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());

        //根据地址id查询地址表
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        +(addressBook.getCityName() == null ? "" :addressBook.getCityName())
                        +(addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        +(addressBook.getDetail() == null ? "": addressBook.getDetail()));

        //4.2 设置总金额
        orders.setAmount(sumAmount);

        //5.调用orderDetailservice的保存方法，将订单明细数据保存到order_detail表中
        orderDetailService.saveBatch(orderDetailList);

        //6.调用自身的保存方法，将订单数据保存到orders表中
        this.save(orders);

        //7.清空购物车(清空当前用户下的购物车)
        shoppingCartService.remove(cartWrapper);
    }
}
